/*************************************************************************
	> File Name: getitimer.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Mon 30 Jun 2014 08:14:06 PM CST
 ************************************************************************/

#include"time.h"
void dealing(int sig)
{
    if(sig==SIGALRM)
    {
        printf("\n\e[42mTime Is Out\e[0m\n");
        exit(0);
    }
    return;
}
int main(int argc,char *argv[])
{
    if(argc<2)
    {
        printf("\n%s number\n",argv[0]);
        _exit(0);
    }
    printf("\e[36m%s\e[0m's PID: %d\n",argv[0],getpid());
    //int which; //value in ITIMER_REAL/ITIMER_VIRTUAL/ITIMER_PROF
    struct itimerval new_value,current_value;
    struct sigaction act;
    sigset_t set;
    //int i,j;   如果不用软件延时,可以用sigqueue发送SIGALRM显示剩余时间

    sigemptyset(&set);
    act.sa_handler=dealing;
    act.sa_mask=set;
    act.sa_flags=0;

    new_value.it_interval.tv_sec=0; //it_interval 的两个值都为0则是一次性定时器
    new_value.it_interval.tv_usec=0; //若此处为1则每隔1s或1us发送一次SIGALRM信号
    new_value.it_value.tv_usec=0; //定时的us
    new_value.it_value.tv_sec=atoi(argv[1]); //定时器定时的s


    printf("this program will sleep %ss\n",argv[1]);

    if((setitimer(ITIMER_REAL,&new_value,NULL))==-1)
    {
        perror("-->:");
        _exit(errno);
    }
    else
    {
        if(sigaction(SIGINT,&act,NULL)==-1) //仅仅调用dealing作return返回
        {
            perror("-->:");
            _exit(errno);
        }
        if(sigaction(SIGALRM,&act,NULL)==-1) //在dealing里面作打印处理
        {
            perror("-->:");
            _exit(errno);
        }
    }
    for(;;)
    {
        if(getitimer(ITIMER_REAL,&current_value)==-1) //获取当前剩余时间
        {
            perror("getitimer-->");
            _exit(errno);
        }
        else
        {
            printf("the rest time is -->:%d.%d\n",current_value.it_value.tv_sec,current_value.it_value.tv_usec);
        }
        pause(); // 这个和下面的判断是有必要的,当使用sigqueue或kill 14时
    }
    exit(0);
}
